<?php
namespace app\index\controller;

use app\common\model\ArticleComment;
use app\common\model\Articles;
use think\App;
use think\Controller;
use think\facade\Request;
use think\facade\Url;

class Index extends Controller
{
    protected $article_model;
    protected $article_comment_model;
    public function initialize()
    {
        Url::root('/index.php');
        $this->article_model = new Articles();
        $this->article_comment_model = new ArticleComment();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function index()
    {
        return $this->fetch();
    }


    public function getdata($page=1,$count=10){
        $offset = ($page-1)*$count;
        $data = $this->article_model->limit($offset,$count)->order('id', 'desc')->select();
        $this->success($data);
    }

    public function article_info($aid){
        $article = $this->article_model->find($aid);
        if(!$article){
            $this->redirect("index");
        }
        $article['click_num'] = ['inc', 1];
        $article->save();
        $data = $this->article_model->find($aid);
        $data['body'] = htmlspecialchars_decode($data['body']);
        return $this->fetch('article_info',['data'=>$data]);
    }


    public function comment()
    {
        if(Request::isPost()){
            $data = Request::post();
            $this->article_comment_model->save($data);
            $this->success('评论成功');
        }else{
            $data = input('');
            $offset = ($data['page']-1) * $data['count'];
            $where = array(
                'article_id' => $data['article_id']
            );
            $data = $this->article_comment_model->where($where)->limit($offset,$data['count'])->order('id', 'asc')->select();
            $this->success($data);
        }
    }

}
